﻿using RockBus.BufferManager.Interfaces;
using RockBus.Logging.Interfaces;
using System.Reflection;

namespace RockBus.BufferManager
{
    public class WcfBufferManager : IBufferManager
    {
        public WcfBufferManager(ILogger logger, IBufferManagerConfiguration configuration)
        {
            this.Logger = logger;
            this.Configuration = configuration;
            this.InternalBufferManager = System.ServiceModel.Channels.BufferManager.CreateBufferManager(this.Configuration.MaxBufferPoolSize, this.Configuration.MaxBufferSize);
        }

        private ILogger Logger { get; set; }

        public IBufferManagerConfiguration Configuration { get; private set; }

        private System.ServiceModel.Channels.BufferManager InternalBufferManager { get; set; }

        public void Clear()
        {
            this.InternalBufferManager.Clear();
        }

        public void ReturnBuffer(byte[] buffer)
        {
            this.Logger.LogVerbose(MethodBase.GetCurrentMethod(), "Returning buffer with HashCode {0} and size {1}", buffer.GetHashCode(), buffer.Length);
            this.InternalBufferManager.ReturnBuffer(buffer);
        }

        public byte[] TakeBuffer(int bufferSize)
        {
            byte[] buffer = this.InternalBufferManager.TakeBuffer(bufferSize);
            this.Logger.LogVerbose(MethodBase.GetCurrentMethod(), "Taking buffer with HashCode {0} and size {1}", buffer.GetHashCode(), buffer.Length);
            return buffer;
        }
    }
}